#!/usr/bin/env python
# -*- coding: utf-8 -*-

# from .basemodel import Model

from .models import Model


class Env(object):
    def __init__(self, rpc, models=None):
        self.rpc = rpc
        if not models:
            models = []

        env = dict((model._name, model) for model in models)
        self._env = env

        self._allowed_company_id = None

    @property
    def version(self):
        return self.rpc.version

    @property
    def sid(self):
        return self.rpc.sid

    @property
    def session(self):
        return self.rpc.session

    @property
    def allowed_company_id(self):
        return self._allowed_company_id

    @allowed_company_id.setter
    def allowed_company_id(self, value):
        self._allowed_company_id = value

    def __getitem__(self, index):
        # print('env, name, ', index)
        MyModel = self._env.get(index) or Model

        model = hasattr(
            MyModel, '_inherit') and self[MyModel._inherit].model or index

        metadata = self.get_metadata(MyModel)

        return MyModel(model, self, metadata)

    def get_metadata(self, MyModel):
        # print('in env, get_metadata 1 ', MyModel)
        me_meta = MyModel._get_metadata()
        if not hasattr(MyModel, '_inherit'):
            return me_meta

        # print('in env, get_metadata 3 MyModel._inherit, ', MyModel._inherit)
        Parent_Model = self._env[MyModel._inherit]
        # print('in env, get_metadata 4 Parent_Model, ', Parent_Model)

        p_meta = self.get_metadata(Parent_Model)
        # print('----in _get_metadata, parent meta ', p_meta)
        # print('---in _get_metadata, me meta ', me_meta)
        return mergeDict(p_meta,  me_meta)

    def ref(self, xmlid):
        res = self['ir.model.data'].xmlid_to_res_model_res_id(xmlid, True)
        return res[1]


def mergeDict(dict1, dict2):
    ret = {}

    for k, v in dict1.items():
        if isinstance(v, dict):
            if k not in dict2.keys():
                ret[k] = v
            else:
                ret[k] = mergeDict(v, dict2[k])
        else:
            new_v = v
            if k in dict2.keys():
                new_v = dict2[k]
            ret[k] = new_v

    ret2 = {}

    for k, v in dict2.items():
        if k not in ret:
            ret2[k] = v
    ret.update(ret2)

    return ret
